<template>
    <div :class="'assess_form early ' + formType">
        <div class="form_title">XXXX医疗机构</div>
        <div class="form_name">{{ title }}</div>
        <div class="form_patient_bar">
            <div v-for="(item, index) in patientStruct" :key="index" class="patient_info_item">
                <div class="item_label">{{ item.label }}：</div>
                <div class="item_value">{{ formType == 'template' ? item.label : patientInfo[item.key] }}{{ item.unit }}</div>
            </div>
        </div>
        <el-form ref="assessForm" :model="selfFormData" :rules="rules" class="form_question_info">
            <template v-for="(item, index) in assessFormStruct">
                <div v-if="item.title" :key="'title_' + index" class="question_title">{{ item.title }}</div>
                <template v-else>
                    <el-form-item :key="'item_' + index" :label="item.label + '：'" :prop="item.key"
                        class="question_item">
                        <template v-if="formType === 'edit' || formType == 'template'">
                            <el-input v-if="item.controlType === 'input'" v-model="selfFormData[item.key]" :placeholder="item.label" :disabled="formType == 'template'"/>
                            <el-input v-else-if="item.controlType === 'textarea'" v-model="selfFormData[item.key]" :placeholder="item.label" :disabled="formType == 'template'"
                                type="textarea" :rows="3" />
                            <el-select v-else-if="item.controlType === 'select'" v-model="selfFormData[item.key]" :placeholder="'请选择' + item.label" :disabled="formType == 'template'"
                                :multiple="item.isMultiple">
                                <el-option v-for="option in options[item.optionsKey]" :key="option.aid"
                                    :label="option.realname" :value="option.aid" />
                            </el-select>
                            <span v-else>{{ formType == 'template' && item.key ? item.label : getViewValue(item.key) }}</span>
                        </template>
                        <span v-else>{{ getViewValue(item.key) }}</span>
                    </el-form-item>
                    <div v-if="item.children && item.children.length" :key="'children_' + index" class="question_item">
                        <el-form-item v-for="(child, childIndex) in item.children" :key="'child_' + childIndex"
                            :label="child.label + '：'" :prop="child.key" class="question_sub_items">
                            <template v-if="formType === 'edit' || formType == 'template'">
                                <el-input v-if="child.controlType === 'input'" v-model="selfFormData[child.key]" :placeholder="child.label" :disabled="formType == 'template'"/>
                                <el-input v-else-if="child.controlType === 'textarea'" v-model="selfFormData[child.key]" :placeholder="child.label" :disabled="formType == 'template'"
                                    type="textarea" :rows="3" />
                                <el-select v-else-if="child.controlType === 'select'" v-model="selfFormData[child.key]" :placeholder="'请选择' + child.label" :disabled="formType == 'template'"
                                    :multiple="child.isMultiple">
                                    <el-option v-for="option in options[child.optionsKey]" :key="option.aid"
                                        :label="option.realname" :value="option.aid" />
                                </el-select>
                                <span v-else>{{ formType == 'template' && child.key ? child.label : getViewValue(child.key) }}</span>
                            </template>
                            <span v-else>{{ getViewValue(child.key) }}</span>
                        </el-form-item>
                    </div>
                </template>
            </template>
        </el-form>
        <div class="form_sign_info">
            <div class="sign_bar">
                <div class="sign_item">
                    <div class="sign_label">治疗师：</div>
                    <div class="sign_value">{{ formType == 'template' ? '治疗师签名' : therapistNames }}</div>
                </div>
                <div class="sign_item">
                    <div class="sign_label">护士：</div>
                    <div class="sign_value">{{ formType == 'template' ? '护士签名' : nurseNames }}</div>
                </div>
                <div class="sign_item">
                    <div class="sign_label">医师签名：</div>
                    <div class="sign_value">{{ formType == 'template' ? '医师签名' : doctorNames }}</div>
                </div>
            </div>
            <div class="sign_bar" style="justify-content: flex-end;">
                <div class="sign_item">
                    <div class="sign_label">签名时间：</div>
                    <div class="sign_value">{{ formType == 'template' ? '医师签名时间' : selfFormData.evaluateTime }}</div>
                </div>
            </div>
            <div class="sign_bar">
                <div class="sign_item">
                    <div class="sign_label">患方签名：</div>
                    <div class="sign_value" v-if="signType == 1">
                        <template v-if="formType === 'template'">
                            <span>患方签名</span>
                            <span style="margin-left: 10px;">患方指纹</span>
                        </template>
                        <template v-else>
                            <el-image :src="selfFormData.patientSign">
                                <div slot="error">点击签名</div>
                            </el-image>
                            <el-image :src="selfFormData.patientFingerprint">
                                <div slot="error" />
                            </el-image>
                        </template>
                    </div>
                </div>
                <div class="sign_item">
                    <div class="sign_label">与患者关系：</div>
                    <div class="sign_value">
                        <el-select v-if="formType === 'edit' || formType == 'template'" v-model="selfFormData.relationshipWithPatient" :disabled="formType == 'template'"
                            placeholder="请选择与患者关系">
                            <el-option v-for="option in relationList" :key="option.itemName" :label="option.itemName"
                                :value="option.itemName" />
                        </el-select>
                        <span v-else>{{ selfFormData.relationshipWithPatient }}</span>
                    </div>
                </div>
                <div class="sign_item">
                    <div class="sign_label">签名时间：</div>
                    <div class="sign_value">{{ formType == 'template' ? '患方签名时间' : selfFormData.patientSignTime }}</div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import { getEnableAdminsWithRole } from '@/api/treatment/treatment.js'
import { list } from '@/api/system/dictItem'

const initDefaultForm = () => {
    return {
        evaluateAddr: '',
        participantsDoctor: [],
        participantsTherapist: [],
        participantsNurse: [],
        admissionIllness: '',
        nowDiagnosis: '',
        nowPatientSituation: '',
        ptQuestion: '',
        otQuestion: '',
        stQuestion: '',
        careQuestion: '',
        patientFamilyExpect: '',
        directorDoctorSuggestion: '',
        deputyDirectorDoctorSummary: '',
        recentGoals: '',
        longTermGoals: '',
        rehabilitationPlan: '',
        relatedLetters: '',
        relationshipWithPatient: '',
        patientSign: '',
        patientFingerprint: '',
        patientSignTime: '',
        evaluateUser: '',
        evaluateTime: ''
    }
}
const assessFormStruct = [
    {
        label: '时间',
        key: 'evaluateTime'
    },
    {
        label: '地点',
        key: 'evaluateAddr',
        controlType: 'input'
    },
    {
        label: '参加人员',
        children: [
            {
                label: '医生',
                key: 'participantsDoctor',
                controlType: 'select',
                optionsKey: 'doctorList',
                isMultiple: true
            },
            {
                label: '治疗师',
                key: 'participantsTherapist',
                controlType: 'select',
                optionsKey: 'therapistList',
                isMultiple: true
            },
            {
                label: '护士',
                key: 'participantsNurse',
                controlType: 'select',
                optionsKey: 'nurseList',
                isMultiple: true
            }
        ]
    },
    {
        title: '主管医生汇报病史'
    },
    {
        label: '入院病情',
        key: 'admissionIllness',
        controlType: 'textarea'
    },
    {
        label: '目前诊断',
        key: 'nowDiagnosis',
        controlType: 'textarea',
        important: true
    },
    {
        label: '目前患者情况',
        key: 'nowPatientSituation',
        controlType: 'textarea',
        children: [
            {
                label: 'PT问题',
                key: 'ptQuestion',
                controlType: 'textarea'
            },
            {
                label: 'OT问题',
                key: 'otQuestion',
                controlType: 'textarea'
            },
            {
                label: 'ST问题',
                key: 'stQuestion',
                controlType: 'textarea'
            },
            {
                label: '护理问题',
                key: 'careQuestion',
                controlType: 'textarea'
            }
        ]
    },
    {
        label: '患者家属预期',
        key: 'patientFamilyExpect',
        controlType: 'textarea'
    },
    {
        label: '主管医师意见',
        key: 'directorDoctorSuggestion',
        controlType: 'textarea'
    },
    {
        label: '（副）主任医师总结',
        key: 'deputyDirectorDoctorSummary',
        controlType: 'textarea'
    },
    {
        label: '近期目标',
        key: 'recentGoals',
        controlType: 'textarea'
    },
    {
        label: '远期目标',
        key: 'longTermGoals',
        controlType: 'textarea'
    },
    {
        label: '康复计划',
        key: 'rehabilitationPlan',
        controlType: 'textarea'
    },
    {
        label: '相关风险',
        key: 'relatedLetters',
        controlType: 'textarea'
    }
]
export default {
    name: 'Rehab',
    props: {
        title: {
            type: String,
            default: '康复评定表'
        },
        formType: {
            type: String,
            default: 'template' // 表单类型：template：模板，edit：评估，view：详情
        },
        patientInfo: {
            type: Object,
            default: () => ({}) // 患者信息
        },
        doctorType: {
            type: String,
            default: 'hospital' // 医生类型：hospital：住院医生，outpatient：门诊医生，therapists：治疗师
        },
        assessInfo: {
            type: Object,
            default: () => ({}) // 评定表信息
        },
        signType: {
            type: Number,
            default: 1
        }
    },
    data() {
        return {
            assessFormStruct,
            selfFormData: {},
            rules: {
                content: [
                    { required: true, message: '请选择项目', trigger: 'change' }
                ]
            },
            options: {
                doctorList: [],
                nurseList: [],
                therapistList: []
            },
            relationList: []
        }
    },
    computed: {
        patientStruct() {
            if (this.formType === 'edit' || this.formType === 'view') {
                if (['hospital', 'therapists'].includes(this.doctorType)) {
                    return [{
                        label: '姓名',
                        key: 'patientName'
                    }, {
                        label: '性别',
                        key: 'genderName'
                    }, {
                        label: '年龄',
                        key: 'age',
                        unit: '岁'
                    }, {
                        label: '科室',
                        key: 'departmentName'
                    }, {
                        label: '床号',
                        key: 'bedNum'
                    }, {
                        label: '住院号',
                        key: 'admissionNum'
                    }]
                } else {
                    return [{
                        label: '姓名',
                        key: 'patientName'
                    }, {
                        label: '门诊号',
                        key: 'admissionNum'
                    }]
                }
            } else {
                return [{
                    label: '姓名',
                    key: ''
                }, {
                    label: '性别',
                    key: ''
                }, {
                    label: '年龄',
                    key: ''
                }, {
                    label: '科室',
                    key: ''
                }, {
                    label: '门诊号/住院号',
                    key: ''
                }]
            }
        },
        doctorNames() {
            if (this.selfFormData.participantsDoctor && this.selfFormData.participantsDoctor.length) {
                return this.selfFormData.participantsDoctor.map(item => {
                    const doctor = this.options.doctorList.find(doctor => doctor.aid === item)
                    return doctor ? doctor.realname : ''
                }).join(',')
            } else {
                return ''
            }
        },
        therapistNames() {
            if (this.selfFormData.participantsTherapist && this.selfFormData.participantsTherapist.length) {
                return this.selfFormData.participantsTherapist.map(item => {
                    const therapist = this.options.therapistList.find(therapist => therapist.aid === item)
                    return therapist ? therapist.realname : ''
                }).join(',')
            } else {
                return ''
            }
        },
        nurseNames() {
            if (this.selfFormData.participantsNurse && this.selfFormData.participantsNurse.length) {
                return this.selfFormData.participantsNurse.map(item => {
                    const nurse = this.options.nurseList.find(nurse => nurse.aid === item)
                    return nurse ? nurse.realname : ''
                }).join(',')
            } else {
                return ''
            }
        }
    },
    watch: {
        assessInfo: function (val) {
            this.initFormData()
        }
    },
    mounted() {
        this.getDoctorList()
        this.getTherapistList()
        this.getNurseList()
        this.getRelationList()
        this.initFormData()
        console.log(this.patientInfo,"patientInforehab88888");

    },
    methods: {
        getViewValue(key) {
            switch (key) {
                case 'participantsDoctor':
                    return this.doctorNames
                case 'participantsTherapist':
                    return this.therapistNames
                case 'participantsNurse':
                    return this.nurseNames
                default:
                    return this.selfFormData[key]
            }
        },
        initFormData() {
            this.selfFormData = Object.assign(initDefaultForm(), this.assessInfo)
            this.selfFormData.participantsDoctor = this.selfFormData.participantsDoctor.map(item => item.aid || item)
            this.selfFormData.participantsTherapist = this.selfFormData.participantsTherapist.map(item => item.aid || item)
            this.selfFormData.participantsNurse = this.selfFormData.participantsNurse.map(item => item.aid || item)
        },
        getDoctorList() {
            getEnableAdminsWithRole({ roleId: 2 }).then(res => {
                this.options.doctorList = res.content
            })
        },
        getTherapistList() {
            getEnableAdminsWithRole({ roleId: 4 }).then(res => {
                this.options.therapistList = res.content
            })
        },
        getNurseList() {
            getEnableAdminsWithRole({ roleId: 3 }).then(res => {
                this.options.nurseList = res.content
            })
        },
        getRelationList() {
            list({ dicId: 4, page: 1, size: 1000 }).then(res => {
                this.relationList = res.content
            })
        },
        getFormData() {
            return new Promise((resolve, reject) => {
                this.$refs.assessForm.validate((valid) => {
                    if (valid) {
                        resolve({
                            ...this.selfFormData
                        })
                    } else {
                        reject('存在未通过表单校验的数据')
                        return false
                    }
                })
            })
        },
        changeToEstimateList(estimateId, submitForm) {
            const keyList = []
            Object.keys(submitForm).forEach(key => {
                if(submitForm[key]){
                keyList.push({
                    key,
                    value: JSON.stringify(submitForm[key])
                })
                }
            })
            return JSON.stringify({
                estimateId,
                keyList
            })
        },
        async saveLocalFormData(source, patientId, estimateType) {
            let data = await this.getFormData();
            const estimateId = estimateType + 3
            const submitForm = {
                estimateType,
                evaluateSource: source,
                ...data,
                patientSign: '1',
                patientFingerprint: '1',
                patientSignTime: '1'
            }
            localStorage.setItem(`estimate_${source}_${patientId}_${estimateId}`, this.changeToEstimateList(estimateId, submitForm));
        },
    }
}
</script>

<style lang="scss" scoped>
@import url('./style.scss');

.early {
    .form_question_info {
        border-top: 1px solid #333;
        padding-top: 10px;

        .question_title {
            font-size: 16px;
            font-weight: bold;
            margin-bottom: 5px;
        }

        .question_item {
            display: flex;
            flex-wrap: wrap;
            margin-bottom: 5px;

            ::v-deep {
                .el-form-item__label {
                    color: #333;
                    font-weight: bold;
                }

                .el-form-item__content {
                    flex-grow: 1;
                }
            }

            .question_label {
                font-weight: bold;
            }

            .question_sub_items {
                width: 100%;
                margin-bottom: 5px;
                padding-left: 2em;
                display: flex;

                ::v-deep {
                    .el-form-item__label {
                        font-weight: normal;
                    }
                }
            }
        }
    }

    .form_sign_info {
        .sign_bar {
            display: flex;
            justify-content: space-between;

            .sign_item {
                display: flex;
                align-items: center;
                width: 33.33%;
                margin-bottom: 5px;
                padding-right: 10px;

                .sign_label {
                    flex-shrink: 0;
                }
            }
        }
    }

    &.edit {
        .form_question_info {
            .question_item {
                margin-bottom: 18px;

                .question_sub_items {
                    margin-bottom: 18px;
                }
            }
        }
    }
}
</style>
